#include "main.h"
#include "usart.h"
#include "laser_sensor.h"
#include <stdlib.h>

#define STATE_STOP      0
#define STATE_DATA      1
#define STATE_LEVLE     2



uint8_t buffer;
uint16_t data;
uint8_t confidence_level;

//激光传感器用于定位
void laser_sensor_init(void)
{
    //初始化函数
    HAL_UART_Receive_IT(LASER_SENSOR_SERIAL, &buffer, 1);
}
void laser_sensor_read(void)
{
    //中断函数中调用
    static uint8_t data_array[6] = {0};
    static uint8_t confidence_level_array[3] = {0};
    static uint8_t data_position;
    static uint8_t confidence_level_position;

    static uint8_t read_state;
    //按照激光传感器数据帧格式读取
    if(buffer == 0x20 && read_state == STATE_STOP)
    {
        read_state = STATE_DATA;
        //对每个数据帧初始化
        data_position = 0;
        confidence_level_position = 0;
        uint8_t i = 0;
        for(i = 0;i < 6;i++)data_array[i] = 0;
        for(i = 0;i < 3;i++)confidence_level_array[i] = 0;
    }
    else if(buffer != 0x2C && read_state == STATE_DATA)
    {
        data_array[data_position] = buffer;
        data_position++;
    }
    else if(buffer == 0x2C && read_state == STATE_DATA)
    {
        read_state = STATE_LEVLE;
    }
    else if(buffer != 0x0A && read_state == STATE_LEVLE)
    {
        confidence_level_array[confidence_level_position] = buffer;
        confidence_level_position++;
    }
    else if(buffer == 0x0A)
    {
        //读取完一个数据帧，开始处理数据，字符串转数字
        data = atoi((char *)data_array);//有效数据后至少有一个0，等效字符串
        confidence_level = atoi((char *)confidence_level_array);
        read_state = STATE_STOP;
    }
    //读取下一个字节
    HAL_UART_Receive_IT(LASER_SENSOR_SERIAL, &buffer, 1);
}
uint16_t laser_sensor_get_data(void)
{
    return data;
}
uint8_t laser_sensor_get_confidence_level(void)
{
    return confidence_level;
}







